#include<cstdio>//uncle-lu
#include<algorithm>

int F[1010];

int main()
{
	int h1, m1, h2, m2, n;
	scanf("%d:%d %d:%d %d", &h1, &m1, &h2, &m2, &n);
	int t = h2*60 - h1*60 + m2 - m1;
	int v, c, m;
	for (int i = 1; i <= n; i++) 
	{
		scanf("%d %d %d", &v, &c, &m);
		if(m == 0)
		{
			for (int j = v; j <= t; j++) 
				F[j] = std::max(F[j], F[j-v] + c);
		}
		else
		{
			int temp = 1;
			while(temp <= m)
			{
				for (int j = t; j >= v*temp; j--) 
					F[j] = std::max(F[j], F[j-v*temp] + c*temp);
				m -= temp;
				temp <<= 1;
			}
			if(m != 0)
				for (int j = t; j >= v*m; j--) 
					F[j] = std::max(F[j], F[j-v*m] + c*m);
		}
	}

	printf("%d", F[t]);
	return 0;
}
